package com.hhd.pdf.component.branch;

import com.hhd.pdf.CommonUtils;
import com.hhd.pdf.component.AbstractPdfComponent;
import com.hhd.pdf.component.functions.PdfFunctionContext;
import com.hhd.pdf.component.functions.PdfFunctionExecutor;
import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.variable.DynamicFormula;
import com.hhd.pdf.variable.VariableContext;
import com.itextpdf.text.Element;
import org.dom4j.Attribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

@Component
public class IfComponent extends AbstractPdfComponent {

    @Autowired
    @Lazy
    PdfFunctionExecutor pdfFunctionExecutor;

    @Override
    public List<Element> doGenElements(GeneratorContext context) {
        List<Element> res = CommonUtils.newList();

        if (decide(context.getParsingElement(), context.getVariableContext(), context)) {
            List<Element> elements = genChildren(context, context.getParsingElement());
            if (!CommonUtils.isEmpty(elements))
                res.addAll(elements);
        }
        return res;
    }

    private boolean decide(org.dom4j.Element element,
                           VariableContext rootVariableContext,
                           GeneratorContext context) {
        List<Attribute> attributes = element.attributes();
        HashMap<String, Object> variables = new HashMap<>();
        if (CommonUtils.isEmpty(attributes)) {
            attributes = CommonUtils.newList();
        }
        String function = "";
        for (Attribute attribute : attributes) {
            if ("function".equals(attribute.getName())) {
                function = attribute.getText();
                continue;
            }

            String formulaText = attribute.getText();
            if (CommonUtils.isEmpty(formulaText)) {
                continue;
            }


            Object value = executeFormulaValue(rootVariableContext, formulaText);
            variables.put(attribute.getName(), value);
        }

        return pdfFunctionExecutor.exeute(PdfFunctionContext.builder()
                .function(function)
                .element(element)
                .variableContext(rootVariableContext)
                .generatorContext(context)
                .variables(variables)
                .build(), Boolean.class);
    }

    private Object executeFormulaValue(VariableContext rootVariableContext, String formulaText) {
        if (!formulaText.contains("{{")) {
            return formulaText;
        }

        DynamicFormula<Object> formula = DynamicFormula.formula(formulaText, Object.class);
        rootVariableContext.execute(formula);
        return formula.getFormulaValue();
    }

    @Override
    public String getName() {
        return "if";
    }
}
